<template>
		<div>
				<!--面包屑区域-->
				<el-breadcrumb separator-class="el-icon-arrow-right">
						<el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
						<el-breadcrumb-item>商品管理</el-breadcrumb-item>
						<el-breadcrumb-item>商品参数</el-breadcrumb-item>
				</el-breadcrumb>
				<!--卡片视图区域-->
				<el-card>
						<!--头部警告区域-->
						<el-alert
										title="注意：只允许为第三级分类设置相关参数！"
										type="warning"
										:closable="false">
						</el-alert>

						<el-row class="cat_opt">
								<span>请选择商品分类：</span>
								<!--级联选择器渲染-->
								<el-cascader
												v-model="selectCatkeys"
												:options="catList"
												:props="catProps"
												@change="handleChange"
												:clearable="true"
								></el-cascader>
						</el-row>
						<!--tab页签-->
						<el-tabs v-model="activeName" @tab-click="handleTabClick">
								<el-tab-pane label="动态参数" name="many">
										<el-button icon="el-icon-plus" type="primary" size="mini" :disabled="selectCatkeys.length!==3"
																					@click="dialogVisible = true">
												添加参数
										</el-button>
										<!--动态参数表格-->
										<el-table :data="manyTabData" border stripe>
												<!--展开行-->
												<el-table-column type="expand">
														<template v-slot="scope">
																<!--循环渲染tag-->
																<el-tag type="success" v-for="(item,index) in scope.row.attr_vals" :key="index" closable
																								@close="delTag(scope.row,index)">{{ item }}
																</el-tag>
																<!--input 和 按钮动态切换-->
																<el-input
																				class="input-new-tag"
																				v-if="scope.row.inputVisible"
																				v-model.trim="scope.row.inputValue"
																				ref="saveTagInput"
																				size="small"
																				@keydown.enter.native="handleInputConfirm(scope.row)"
																				@blur="handleInputConfirm(scope.row)"
																>
																</el-input>
																<el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag
																</el-button>
														</template>
												</el-table-column>
												<!--索引列-->
												<el-table-column type="index" label="#"></el-table-column>
												<el-table-column label="参数名称" prop="attr_name" align="center"></el-table-column>
												<el-table-column label="操作" align="center">
														<template v-slot:="scope">
																<el-button type="primary" size="mini" icon="el-icon-edit"
																											@click="showEditDialog(scope.row.attr_id)">编辑
																</el-button>
																<el-popconfirm
																				placement="top"
																				confirmButtonText='好的'
																				cancelButtonText='不用了'
																				@onConfirm="sureDelete(scope.row.attr_id)"
																				icon="el-icon-info"
																				iconColor="red"
																				:title="`确定删除 【${scope.row.attr_name}】 吗？`">
																		<el-button style="margin-right: 10px" size="mini" type="danger" slot="reference"
																													icon="el-icon-delete">
																				删除
																		</el-button>
																</el-popconfirm>
														</template>
												</el-table-column>
										</el-table>
								</el-tab-pane>
								<el-tab-pane label="静态属性" name="only">
										<el-button icon="el-icon-plus" type="primary" size="mini" :disabled="selectCatkeys.length!==3"
																					@click="dialogVisible = true">
												添加属性
										</el-button>
										<!--静态属性表格-->
										<el-table :data="onlyTabData" border stripe>
												<el-table-column type="expand">
														<template v-slot="scope">
																<!--循环渲染tag-->
																<el-tag type="success" v-for="(item,index) in scope.row.attr_vals" :key="index" closable
																								@close="delTag(scope.row,index)">{{ item }}
																</el-tag>
																<!--input 和 按钮动态切换-->
																<el-input
																				class="input-new-tag"
																				v-if="scope.row.inputVisible"
																				v-model.trim="scope.row.inputValue"
																				ref="saveTagInput"
																				size="small"
																				@keydown.enter.native="handleInputConfirm(scope.row)"
																				@blur="handleInputConfirm(scope.row)"
																>
																</el-input>
																<el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag
																</el-button>
														</template>
												</el-table-column>
												<el-table-column type="index" label="#"></el-table-column>
												<el-table-column label="参数名称" prop="attr_name" align="center"></el-table-column>
												<el-table-column label="操作" align="center">
														<template v-slot:="scope">
																<el-button type="primary" size="mini" icon="el-icon-edit"
																											@click="showEditDialog(scope.row.attr_id)">编辑
																</el-button>
																<el-popconfirm
																				placement="top"
																				confirmButtonText='好的'
																				cancelButtonText='不用了'
																				@onConfirm="sureDelete(scope.row.attr_id)"
																				icon="el-icon-info"
																				iconColor="red"
																				:title="`确定删除 【${scope.row.attr_name}】 吗？`">
																		<el-button style="margin-right: 10px" size="mini" type="danger" slot="reference"
																													icon="el-icon-delete">
																				删除
																		</el-button>
																</el-popconfirm>
														</template>
												</el-table-column>
										</el-table>
								</el-tab-pane>
						</el-tabs>
				</el-card>

				<el-dialog
								:title="`添加${titleText}`"
								:visible.sync="dialogVisible"
								:close-on-click-modal="false"
								@close="addDialogClosed"
								width="50%">
						<el-form :model="addForm" :rules="addFormRules" ref="ruleForm" label-width="100px" status-icon>
								<el-form-item :label="titleText" prop="attr_name">
										<el-input v-model="addForm.attr_name" clearable></el-input>
								</el-form-item>
						</el-form>
						<span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="sureAdd">确 定</el-button>
            </span>

				</el-dialog>
				<el-dialog
								:title="`修改${titleText}`"
								:visible.sync="editDialogVisible"
								:close-on-click-modal="false"
								@close="editDialogClosed"
								width="50%">
						<el-form :model="editForm" :rules="editFormRules" ref="editRuleForm" label-width="100px" status-icon>
								<el-form-item :label="titleText" prop="attr_name">
										<el-input v-model="editForm.attr_name" clearable></el-input>
								</el-form-item>
						</el-form>
						<span slot="footer" class="dialog-footer">
                <el-button @click="editDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="sureEdit">确 定</el-button>
            </span>

				</el-dialog>
		</div>
</template>

<script>
import $axios from "../../network/request";

export default {
		name: "Params",
		data() {
				return {
						catList: [],
						selectCatkeys: [],
						catProps: {
								expandTrigger: 'hover', value: 'cat_id', label: 'cat_name', children: 'children'
						},
						activeName: "many",
						manyTabData: [],
						onlyTabData: [],
						dialogVisible: false,
						editDialogVisible: false,
						addForm: {
								attr_name: '',
						},
						editForm: {
								attr_name: '',
								attr_id: '',
						},
						addFormRules: {
								attr_name: [
										{required: true, message: `请输入参数名称`, trigger: 'blur'},
										{min: 1, max: 5, message: '长度在 1 到 5 个字符', trigger: 'blur'}
								],
						},
						editFormRules: {
								attr_name: [
										{required: true, message: `请输入参数名称`, trigger: 'blur'},
										{min: 1, max: 5, message: '长度在 1 到 15 个字符', trigger: 'blur'}
								],
						},
						//控制文本框和button的显示
						inputVisible: false,
						//输入框绑定的value
						inputValue: ''
				}
		},
		created() {
				this.init()
		},
		methods: {
				init() {
						$axios({
								method: 'get',
								url: 'categories'
						}).then(res => {
								const {data} = res
								if (data.meta.status !== 200) {
										return this.$message.error("请求数据失败")
								}
								this.catList = data.data
						})
				},
				//级联选择器发生改变发生的事件
				handleChange() {
						this.getParamsData()
				},
				//tab点击事件
				handleTabClick() {
						this.getParamsData()
				},

				getParamsData() {
						//判断选中的是不是三级分类
						if (this.selectCatkeys.length !== 3) {
								this.selectCatkeys = [];
								this.manyTabData = [];
								this.onlyTabData = [];
								return
						}
						$axios({
								method: 'get',
								url: `categories/${this.cateId}/attributes`,
								params: {
										sel: this.activeName
								}
						}).then(res => {
								const {data} = res;
								if (data.meta.status !== 200) {
										return this.$message.error("获取参数列表失败")
								}
								console.log(data.data)
								data.data.forEach(item => {
										item.attr_vals = item.attr_vals ? item.attr_vals.split(" ") : []
										item.inputVisible = false
										item.inputValue = ''
								})
								if (this.activeName === 'many') {
										this.manyTabData = data.data
								} else {
										this.onlyTabData = data.data
								}
						})
				},
				//添加弹窗的关闭事件
				addDialogClosed() {
						this.$refs.ruleForm.resetFields()
				},

				//确定添加事件
				sureAdd() {
						this.$refs.ruleForm.validate(valid => {
								if (valid) {
										$axios({
												method: 'post',
												url: `categories/${this.cateId}/attributes`,
												data: {
														attr_name: this.addForm.attr_name,
														attr_sel: this.activeName
												}
										}).then(res => {
												const {data} = res;
												if (data.meta.status !== 201) {
														return this.$message.error("参数添加失败")
												}
												this.$message.success("添加成功")
												this.dialogVisible = false;
												this.getParamsData();
										})
								}
						})
				},

				//展示修改弹窗
				showEditDialog(attr_id) {
						this.editDialogVisible = true
						$axios({
								method: 'get',
								url: `categories/${this.cateId}/attributes/${attr_id}`,
								params: {
										attr_sel: this.activeName
								}
						}).then(res => {
								const {data} = res
								if (data.meta.status !== 200) {
										return this.$message.error("获取参数数据失败")
								}
								this.editForm = data.data
						})
				},
				//编辑弹窗的关闭事件
				editDialogClosed() {
						this.$refs.editRuleForm.resetFields()
				},
				//确定修改时间
				sureEdit() {
						this.$refs.editRuleForm.validate(valid => {
								if (valid) {
										$axios({
												method: 'put',
												url: `categories/${this.cateId}/attributes/${this.editForm.attr_id}`,
												data: {
														attr_name: this.editForm.attr_name,
														attr_sel: this.activeName,
												}
										}).then(res => {
												const {data} = res;
												if (data.meta.status !== 200) {
														return this.$message.error("更新失败")
												}
												this.$message.success("更新成功")
												this.editDialogVisible = false;
												this.getParamsData()
										})
								}
						})
				},
				//删除事件
				sureDelete(attr_id) {
						$axios({
								method: 'delete',
								url: `categories/${this.cateId}/attributes/${attr_id}`
						}).then(res => {
								const {data} = res
								if (data.meta.status !== 200) {
										return this.$message.error("删除失败")
								}
								this.$message.success("删除成功")
								this.getParamsData()
						})
				},
				//输入框输入焦点或者按回车键发生的事件
				handleInputConfirm(row) {
						if (row.inputValue.trim().length === 0) {
								row.inputVisible = false;
								row.inputValue = '';
								return
						}
						row.inputVisible = false
						row.attr_vals.push(row.inputValue.trim())
						row.inputValue = ''
						$axios({
								method: 'put',
								url: `categories/${this.cateId}/attributes/${row.attr_id}`,
								data: {
										'attr_name': row.attr_name,
										'attr_sel': this.activeName,
										'attr_vals': row.attr_vals.join(" ")
								}
						}).then(res => {
								const {data} = res
								if (data.meta.status !== 200) {
										return this.$message.error("更新失败")
								}
								this.$message.success("更新成功")
						})
				},
				showInput(row) {
						row.inputVisible = true;
						//让文本框自动获得焦点
						// this.$nextTick当页面中的dom被重新渲染之后，就会执行回调函数
						this.$nextTick(() => {
								this.$refs.saveTagInput.$refs.input.focus();
						});
				},
				delTag(row, v) {
						row.attr_vals.splice(v, 1)
						$axios({
								method: 'put',
								url: `categories/${this.cateId}/attributes/${row.attr_id}`,
								data: {
										'attr_name': row.attr_name,
										'attr_sel': this.activeName,
										'attr_vals': row.attr_vals.join(" ")
								}
						}).then(res => {
								const {data} = res
								if (data.meta.status !== 200) {
										return this.$message.error("更新失败")
								}
								this.$message.success("更新成功")
						})
				}
		},
		computed: {
				cateId() {
						if (this.selectCatkeys.length === 3) {
								return this.selectCatkeys[this.selectCatkeys.length - 1]
						}
						return null
				},
				titleText() {
						if (this.activeName === 'many') {
								return "动态参数"
						} else {
								return "静态属性"
						}
				}
		},
}
</script>

<style scoped>
.cat_opt {
		margin: 15px 0px;
}

.input-new-tag {
		width: 100px;
}
</style>
